import React, {Component, ComponentClass} from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Block, Picker, Image} from '@tarojs/components'
import {AtIcon, AtDrawer, AtTabs} from 'taro-ui';
import {vcmonitor} from "../../../utils/tools";
import Screen from "../../components/screen/screen";
import {VERIFIER_ORDER_LIST, MARKETPERFORMANCE_APP_ALL_SITE, IDENTITY, PRODUCT_ORDER_LIST} from '../../../constants/api'
import GzhAuth from "../../../components/gzh-auth/gzh-auth";
import {user} from "../../../utils/user.service";
import {http} from "../../../utils/http";
import Water from "../../components/water-mark/index";
import './index.scss'

type PageOwnProps = {};
type PageState = {
  listData: any
  drawerShow: boolean
  distributors: any
  options: object
  options1: object
  formData: any
  supplierList: any
  supplierIndex: any
  tabList: any
  current: any
}

class Index extends Component {
  state: PageState = {
    listData: [],
    drawerShow: false,
    supplierList: [],
    current: 0,
    tabList: [
      {title: '核销员统计'},
      {title: '供应商统计'}
    ],
    options: [
      {
        title: '站点',
        type: 'tag',
        key: 'tag',
        active: 0,
        data: []
      },
      {
        title: '姓名',
        type: 'input',
        placeholder: '请输入要搜索的姓名',
        key: 'name'
      },
      {
        title: '手机号',
        type: 'input',
        placeholder: '请输入要搜索的手机号',
        key: 'phone',
        isNumber: true
      },
      {
        title: '门店',
        type: 'input',
        placeholder: '请输入要搜索的门店名称',
        key: 'store'
      }
    ],
    options1: [
      {
        title: '站点',
        type: 'tag1',
        key: 'tag1',
        active: 0,
        data: []
      },
      {
        title: '商品名称',
        type: 'input',
        placeholder: '请输入要搜索的商品名称',
        key: 'product_name'
      },
      {
        title: '门店',
        type: 'input',
        placeholder: '请输入要搜索的门店名称',
        key: 'store'
      }
    ],
    formData: {
      user_name: '',
      user_phone: '',
      sid: '',
      store: '',
      endDate: '',
      startDate: ''

    },
    distributors: '',
    supplierIndex: 0
  }

  async UNSAFE_componentWillMount() {
    // 获取供应商
    const res = await http.HGet(IDENTITY);
    const supplierList = res.data.superCheckerList;
    this.setState({
      supplierList
    }, () => {
      this.onChange({
        detail: {
          value: 0
        }
      });
    });
    const query: any = Taro.getCurrentInstance().router.params;
    const supplierId = query.supplierId;
    const {formData}: any = this.state
    if (supplierId) {
      formData.supplier_id = supplierId;
    }
    this.setState({
      supplierList,
      formData
    }, () => {
      setTimeout(() => {
        this.onChange({
          detail: {
            value: 0
          }
        });
      }, 300);
    });
  }

  onChange(e) {
    const {supplierList, formData}: any = this.state;
    const supplierIndex = Number(e.detail.value);
    const distributors = supplierList && supplierList[supplierIndex].company;
    formData.supplier_id = supplierList && supplierList[supplierIndex].supplier_id;
    this.setState({
      supplierIndex,
      distributors,
      formData
    }, () => {
      this.getData(true);
    });
  }

  async componentDidShow() {
    vcmonitor(this)
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        user.jumpLogin()
      }, 1500)
      return
    }
    const siteRes = await http.HGet(MARKETPERFORMANCE_APP_ALL_SITE, this.state.formData)
    if (siteRes) {
      let {options, options1} = this.state
      options = options || [];
      options[0].data = siteRes.data
      options1[0].data = siteRes.data
      this.setState({
        options,
        options1
      });
    }
  }

  async getData(isReset = false) {
    let {current, formData, listData} = this.state;
    const api = current == 0 ? VERIFIER_ORDER_LIST : PRODUCT_ORDER_LIST;
    Taro.showLoading({title: '加载中...'});
    const res = await http.HGet(api, formData);
    if (res) {
      if (isReset) {
        listData = res.data.check_conductor_list || res.data.goods_list;
      } else {
        listData = listData.concat(res.data.check_conductor_list || res.data.goods_list);
      }
      this.setState({
        listData
      });
    }
    Taro.hideLoading();
  }

  // 开始时间
  changeStart(date) {
    const formData = this.state.formData;
    const options = this.state.options;
    formData.startDate = date;

    // 筛选数据返回
    this.setState({
      formData,
      options
    });
    this.getData(true)
  }

  // 结束时间
  changeEnd(date) {
    const formData = this.state.formData;
    const options = this.state.options;
    formData.endDate = date;

    // 筛选数据返回
    this.setState({
      formData,
      options
    });
    this.getData(true)
  }

  // 关闭筛选
  setDrawer(drawerShow) {
    this.setState({
      drawerShow
    });
  }

  // 监听抽屉返回数据
  screenChange(v, k, i) {
    const formData = this.state.formData;
    const current = this.state.current;
    const options = this.state.options;
    const options1 = this.state.options1;
    // 核销员
    if (k === 'tag') {
      formData.sid = v;
    }
    if (k === 'name') {
      formData.user_name = v;
    }
    if (k === 'phone') {
      formData.user_phone = v;
    }
    if (k === 'store') {
      formData.store = v;
    }
    if (k == 'tag' || k == 'tag1') {
      if (current == 0) {
        options[i].active = v;
      } else {
        options1[i].active = v;
      }
    }
    // 商品
    if (k === 'tag1') {
      formData.location = v;
    }
    if (k === 'bn_id') {
      formData.search_bd_id = v;
    }
    if (k === 'product_name') {
      formData.productName = v;
    }
    // 筛选数据返回
    this.setState({
      formData,
      options,
      options1
    });
    this.getData(true)
  }

  handleClick(value) {
    const formData = this.state.formData;
    formData.startDate = '';
    formData.endDate = '';
    this.setState({
      current: value,
      listData: [],
      formData
    }, () => this.getData(true));
  }

  // 截取名字
  getName(name) {
    if (name) {
      return name.length < 31 ? name : name.substr(0, 31) + '...';
    }
    return ''
  }

  render() {
    const {
      listData,
      options1,
      drawerShow,
      options,
      distributors,
      supplierList,
      supplierIndex,
      tabList,
      current,
      formData
    }: any = this.state;
    const dataColor = Taro.getStorageSync('colorData');
    return (
      <View className='vedrifcation'>
        <GzhAuth />
        <Water />
        <View className='distributors'>
          <View className='distributors-text'>
            {distributors}
          </View>
          <Picker
            value={supplierIndex}
            range={supplierList}
            rangeKey='company'
            onChange={this.onChange.bind(this)}
            mode='selector'
          >
            <View
              className='distributors-btn'
              style={`border: solid 1px ${dataColor.titleColor}; color: ${dataColor.titleColor};`}
            >
              切换
            </View>
          </Picker>
        </View>
        <AtTabs current={current} tabList={tabList} onClick={this.handleClick.bind(this)} />
        <View className='product-item-right t-a-l flex'>
          <Picker
            mode='date'
            onChange={
              ({detail: {value}}) => this.changeStart(value)
            }
            value={formData.startDate}
            className='flex-3'
          >
            <View className='product-item-right f-j-c f-26 w-100 p-r-0'
              style={`color:${formData.startDate ? '#000' : '#c5c5c5'};`}
            >
              {formData.startDate || '选择时间'}
            </View>
          </Picker>
          <View className='product-item-right p-a f-s-26'>至</View>
          <Picker
            mode='date'
            onChange={
              ({detail: {value}}) => this.changeEnd(value)
            }
            value={formData.endDate}
            className='flex-3'
          >
            <View className='product-item-right f-j-c f-26 w-100 p-r-0'
              style={`color:${formData.endDate ? '#000' : '#c5c5c5'};`}
            >
              {formData.endDate || '选择时间'}
            </View>
          </Picker>
        </View>
        <View className='select'>
          <AtIcon size='12' value='icon icon-shaixuan-01' className='m-r-10' />
          <Text className='select-text' onClick={() => this.setDrawer(true)}>
            筛选
          </Text>
        </View>
        <View className='list'>
          {
            current === 0 ? <Block>{
              listData && listData.length > 0 && listData.map((item, index) => {
                return (
                  <Block key={index}>
                    <View className='list-item'>
                      <Text className='list-item-name'>{item.name}</Text>
                      <Text className='line'>|</Text>
                      <Text className='list-item-phone'>{item.phone}</Text>
                      <View className='list-item-position'>
                        <AtIcon prefixClass='car' size='12' value='icondizhi' className='m-r-10' />
                        {item.store_name}
                      </View>
                      <View className='list-item-count'>
                        核销数：<Text className='count'>{item.sum_check_num}</Text>
                      </View>
                    </View>
                  </Block>
                )
              })
            }</Block> : <Block>
              {
                listData && listData.length > 0 && listData.map((item, index) => {
                  return (
                    <Block key={index}>
                      <View className='list-item'>
                        <View className='list-item-header'>
                          <View className='list-item-header-left'>
                            <View className='list-item-header-left-image'>
                              <Image src={item.default_image} style='width:100% ; height:100%' />
                            </View>
                          </View>
                          <View className='list-item-header-right'>
                            <View className='list-item-header-right-name'>
                              {this.getName(item.name)}
                            </View>
                            <View className='list-item-header-right-index'>
                              编号：{item.no}
                            </View>
                            <View className='list-item-header-right-position'>
                              <AtIcon size='12' value='icon-a-2tubiaozhizuomoban-011' className='m-r-10' />
                            </View>
                          </View>
                        </View>
                        <View className='list-item-count'>
                          核销数：<Text className='count'>{item.sum_check_num}</Text>
                        </View>
                      </View>
                    </Block>
                  )
                })
              }
            </Block>
          }
        </View>
        <AtDrawer
          show={drawerShow}
          mask
          onClose={this.setDrawer.bind(this, false)}
          right
        >
          <Screen
            options={current == 0 ? options : options1}
            onChange={this.screenChange.bind(this)}
          />
        </AtDrawer>
      </View>
    );
  }
}

export default Index as ComponentClass<PageOwnProps, PageState>
